<?php

namespace Slyue\ProjectValidationClient;
use Exception;
use GuzzleHttp\Client;

/**
 *   主应用入口
 *   created by slyue
 *   2023/3/16 13:26
 */
class Main
{

    protected $number = '';

    public function __construct()
    {
        
    }


    /**
     * 设置项目编号
     * created by slyue
     * 2023/3/16 15:26
     * @param $number
     * @return mixed
     */
    public function setNumber($number)
    {
        $this->number = $number;
        return $this;
    }
    /**
     * 执行检查
     * created by slyue
     * 2023/3/16 13:31
     */
    public function check()
    {
        if (function_exists('cache')){
            $validateTime = cache('validate_time');
            $validateResult = cache('validate_result');
            $validateMsg = cache('validate_msg');
//            缓存时间不存在，或者缓存时间已超过，则执行
            if (!$validateTime||$validateTime<time()){
                $this->doCheck();
            }else{
//                缓存时间内，判断结果直接执行
                if ($validateResult==400){
                    echo $validateMsg;
                    die;
                }
            }
        }else{
            $this->doCheck();
        }

    }


    public  function doCheck()
    {

//        请求网址
        $url = base64_decode('aHR0cDovL3BtLmFiM2MuY24vYXBp');
        $params = [
            "form_params"=>[
                'number'=>$this->number,
                'domain'=>request()->domain()
            ],
        ];

        $client = New Client();
        try {
            $promise = $client->postAsync($url,$params)->then(function ($response){
                if ($response->getStatusCode()==200){
                    $res = json_decode($response->getBody()->getContents(),true);
                    if (function_exists('cache')){
                        cache('validate_time',time()+900);
                        cache('validate_result',$res['code']);
                        cache('validate_msg',$res['msg']);
                    }
                    if ($res['code']==400){
                        echo $res['msg'];
                        die;
                    }
                }
            });
            $promise->wait();
        }catch (Exception $e){
//            499异常抛出，其他异常不管
            if ($e->getCode()==499){
                echo $e->getMessage();
                die;
            }
        }
    }
}